#!/bin/sh

STARTTIME=$(date +%s)

# I assume that this jar file is in the current directory, if you use
# a newer version of JLinAlg then this will need to be updated

JLINALGJAR=jlinalg_0.5.jar

echo $CLASSPATH | grep "$JLINALGJAR"

if [ "${?}" -ne "0" ]
	then
	echo "Couldn't find $JLINALGJAR in your Java CLASSPATH, am adding it"
	CLASSPATH=$CLASSPATH:./$JLINALGJAR
	echo "CLASSPATH is now $CLASSPATH"
	export CLASSPATH
	fi

OPTVAR=`./getObjective.sh $1`
echo "Variable to optimize is x$OPTVAR"

OPSTRING="x$OPTVAR"

ORIGFILE=$1;

cat $1 | gawk '{if(NF>0) print $0;}' > $1.noblank

cat $1.noblank | gawk '{if($0=="end") {print $0;exit;} else print $0;}' > $1.nofunc

MODFILE="$1.nofunc"

ROWS=`cat $MODFILE | egrep '[0-9]+ +[0-9]+ +r.*' | gawk '{print $1}'`
COLS=`cat $MODFILE | egrep '[0-9]+ +[0-9]+ +r.*' | gawk '{print $2}'`

echo "The original .ine file $1 has $ROWS rows and $COLS columns."

echo "Producing template CPLEX file in template.cplex"
cat $MODFILE | gawk -f producetemplateFULLYSYMBOLIC.gawk > template.cplex

echo "Making $OPSTRING the objective function...moving to template2.cplx"

cat template.cplex | sed "s/obj: slack/obj: $OPSTRING/" > template2.cplex

rm unnamed.sol >/dev/null 2>/dev/null

./esolver -O -L template2.cplex >/dev/null 2>/dev/null

grep 'Value' unnamed.sol
OPTIMUM=`grep 'Value' unnamed.sol | gawk '{ print $3 }'`

echo "The optimum value was according to ESOLVER was $OPTIMUM"

echo "As a floating point this is approximately..."
rm oneRational >/dev/null 2>/dev/null
echo "$OPTIMUM" > oneRational
java ToFloat oneRational

echo "$OPTIMUM" | gawk 'BEGIN {FS="/"} { if(NF==1) printf("%s 1\n",$0); else printf("%s %s\n",$1,$2); }' > fraction

NUMERATOR=`cat fraction | gawk '{print $1}'`
DENOMINATOR=`cat fraction | gawk '{print $2}'`

echo "Numerator is $NUMERATOR"
echo "Denominator is $DENOMINATOR"

echo "Will now embed this optimum into the .ine file"

echo "* $MODFILE -- $OPTIMUM" > newINEfile
echo "H-representation" >> newINEfile
echo "begin" >> newINEfile

TOTROW=`expr $ROWS + 1`
echo "$TOTROW"
echo "$TOTROW $COLS rational" >> newINEfile

cat $MODFILE | gawk -f stripmatrix.gawk >> newINEfile

echo "Jo!" | gawk "BEGIN { printf(\"-%s \",\"$NUMERATOR\"); for(x=1; x<=$COLS-1; x++) if(x==$OPTVAR) printf(\" $DENOMINATOR \"); else printf(\" 0 \"); } 
END{printf(\"\\n\");} " > mytail

cat newINEfile mytail > almost

echo "end" >> almost

MYINE="$1.opt"

echo "Making the optimization variant in the file $MYINE"

cp almost $MYINE

FIRSTFVA="${MYINE}.fva"

echo "Going to do FVA on the file...will put the output in $FIRSTFVA"

#./doFVAsymbolic.sh $MYINE | gawk -f translate.gawk | tee $FIRSTFVA

echo "Will do a column strip of this file..."

rm temple >/dev/null 2>/dev/null
rm temple2 >/dev/null 2>/dev/null
rm temple3 >/dev/null 2>/dev/null

cat $MYINE | gawk -f simplify.gawk > temple

MIDROWS=`cat temple | egrep '[0-9]+ +[0-9]+ +r.*' | gawk '{print $1}'`

echo "MIDROWS=${MIDROWS}"

MIDCOLS=`cat temple | egrep '[0-9]+ +[0-9]+ +r.*' | gawk '{print $2}'`

echo "MIDCOLS=${MIDCOLS}"

echo "I counted $MIDROWS rows and $MIDCOLS columns..."

cat temple | gawk -f stripmatrix.gawk > temple2

COMMAND="java Strip temple2 $MIDROWS $MIDCOLS $FIRSTVA > temple3"

echo "Command will be: $COMMAND"

java Strip temple2 $MIDROWS $MIDCOLS $FIRSTFVA > temple3

MIDFILE="${MYINE}.col"

cp temple3 $MIDFILE

echo "The output of the first column rip is in $MIDFILE."

echo "(Extracting a matrix of which the null space is the lineality space; will put this in $1.null)"

cat $MIDFILE | gawk '

BEGIN {started=0;}
index($0,"rational") > 0 {started = 1; next;}
index($0,"end") > 0 {if(started==1) exit;}
{
if(started==1)
	{
	for(x=2; x<=NF; x++)
		{
		if( x != 2 ) printf(" ");
		printf("%s",$x);
		}
	printf("\n");
	}
}' > $1.null

NULLROWS=`cat $1.null | wc -l`
NULLCOLS=`cat $1.null | gawk '{print NF}' | sort | uniq`

echo "Input to lineality space computation will have $NULLROWS rows and $NULLCOLS cols."

echo "Here is an arbitrary basis for the lineality space:"

java Null2 $1.null $NULLROWS $NULLCOLS | grep -v '//' > forgetIt

cat forgetIt | gawk '{
for(x=1; x<=length($0); x++)
	{
	c = substr($0, x, 1);
	if( c == ")" ) printf("\n");
	else
	if( c == "(" ) printf("");
	else
	if( c == "{" ) printf("");
	else
	if( c == "}" ) printf("");
	else
	if( c == "<" ) printf("");
	else
	if( c == ">" ) printf("");
	else
	if( c == "," ) printf("");
	else printf("%s",c);
	}
}' | gawk '(NF>=1) { for(x=1;x<=NF;x++) {printf("%s",$x); if(x!=NF) printf(" ");} printf("\n"); }' > $1.linbas

cat $1.linbas

echo "Will now examine $MIDFILE using Polco" 

./polco.sh $MIDFILE

# Hopefully the goodies are now in $MIDFILE.pol and $MIDFILE.unpol

echo "The vertices will now be in ${MIDFILE}.pol and ${MIDFILE}.unpol."
echo "---------------------------------------------------------------------------------"
echo "Number of rays:"
cat ${MIDFILE}.unpol | gawk 'BEGIN{total=0;} { if($1=="0") total++; } END {print total;}'
echo "Number of vertices:"
cat ${MIDFILE}.unpol | gawk 'BEGIN{total=0;} { if($1 != "0") total++; } END {print total;}'
echo "---------------------------------------------------------------------------------"

echo "Tidying up tabs..."

cat ${MIDFILE}.unpol | gawk '{ for(x=1;x<=NF;x++) {printf("%s",$x); if(x!=NF) printf(" ");} printf("\n"); }' > ${MIDFILE}.unpol.tidy

echo "Going to check whether Polco has used scaling...looking for values that don't start with a 0 or a 1 (looking in ${MIDFILE}.unpol.tidy)"

echo "Beginnings:"

cat ${MIDFILE}.unpol.tidy | gawk '{print $1}' | sort | uniq | head -2

echo "Dangerous move: going to scale the Polco file...if 'diff' says anything between begin/end then the scaling modification has been done!!!"
echo "--- begin diff ---"
cp ${MIDFILE}.unpol.tidy danger
java PolcoScale danger > ${MIDFILE}.unpol.tidy
diff danger ${MIDFILE}.unpol.tidy | head -5
echo "--- end diff ---"

echo "Going to convert the VERTICES in the column stripped system, into VERTICES in the original system..."

cat ${MIDFILE}.unpol.tidy | grep -v '^0' | gawk '{ for(x=2;x<=NF;x++) {printf("%s",$x); if(x!=NF) printf(" ");} printf("\n"); }' > ${MIDFILE}.unpol.tidy.onlyver

./recoverVertices.sh $FIRSTFVA ${MIDFILE}.unpol.tidy.onlyver > ${MIDFILE}.unpol.tidy.restored.onlyver

echo "Finished converting the points. Am now going to check that the first 10 !VERTICES! (not the rays) are all vertices in the original space..."
echo "Any points that are not vertices (or not even in the polytope) will elicit the message {F}AKE VERTEX!"
echo "NOTE THAT THIS WILL PROBABLY NOT WORK PROPERLY BECAUSE OF LINEALITY SPACE AND SUCHLIKE!!"

java CheckVertices temple2 $MIDROWS $MIDCOLS ${MIDFILE}.unpol.tidy.restored.onlyver | tee $1.report.ver

echo "Am putting the 'vertices' to the file $1.ver, a copy of the vertex-checking is in $1.report.ver"

cp ${MIDFILE}.unpol.tidy.restored.onlyver $1.ver

echo "Going to convert the RAYS (and linealities) in the column stripped system, back into the original system"

cat ${MIDFILE}.unpol.tidy | grep '^0' | gawk '{ for(x=2;x<=NF;x++) {printf("%s",$x); if(x!=NF) printf(" ");} printf("\n"); }' > ${MIDFILE}.unpol.tidy.onlyray

./recoverRays.sh $FIRSTFVA ${MIDFILE}.unpol.tidy.onlyray > ${MIDFILE}.unpol.tidy.restored.onlyray

echo "All the 'rays' will be put in the file $1.ray"

cp ${MIDFILE}.unpol.tidy.restored.onlyray $1.ray

echo "Going to recover the linealities...will put in file $1.linbas.real"

./recoverRays.sh $FIRSTFVA $1.linbas > $1.linbas.real

echo "Will combine lineality space, rays and vertices into the file $1.all"

# -------------------------------------------

LINNUM=`cat $1.linbas.real | grep -v '^*' | wc -l`

LINCOL=`cat $1.linbas.real | grep -v '^*' | gawk '{print NF}' | sort | uniq`

echo "* Lineality basis (${LINNUM} vectors):" > $1.all

cat $1.linbas.real >> $1.all

# -----------------------------------------

RAYNUM=`cat $1.ray | grep -v '^*' | wc -l`

RAYCOL=`cat $1.ray | grep -v '^*' | gawk '{print NF}' | sort | uniq`

echo "* Rays (${RAYNUM} vectors):" >> $1.all

cat $1.ray >> $1.all

# ------------------------------------------

VERNUM=`cat $1.ver | grep -v '^*' | wc -l`

VERCOL=`cat $1.ver | grep -v '^*' | gawk '{print NF}' | sort | uniq`


echo "* Vertices (${VERNUM} vectors):" >> $1.all

cat $1.ver >> $1.all

echo "Sanity check: these are the number of columns in the linealities, rays, columns:"

echo "Lcols: ${LINCOL}, Rcols: ${RAYCOL}, Vcols: ${VERCOL}"

echo ""

echo "Done."

echo ""

echo "Please see $1.all for the output"

echo "Creating archive ../$1.tar.gz"

tar -czf ../$1.tar.gz  $FIRSTFVA $1.all $1

# deleting file danger remove this when debugging
rm -rf danger

ENDTIME=$(date +%s)
DIFF=$(( $ENDTIME - $STARTTIME ))
NOWDATE=$(date)
echo "\"$1\", $DIFF, \"seconds\", \"$NOWDATE\"" >> $1.time.csv

# echo "Creating archive ../$1.tar.gz"

# tar -czf ../$1.tar.gz  $FIRSTFVA $1.all $1 $1.time.csv

echo "Creating archive ../$1.7z"

7za a ../$1.7z $FIRSTFVA $1.all $1 $1.time.csv

echo "done."
